import React, { useState, useRef } from 'react';
import { View, Text, TouchableOpacity, TextInput, Keyboard, StyleSheet, ScrollView } from 'react-native';
import { adapt, adaptFontSize } from '../../ulits/Adapt';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import EmojiPanel from './EmojiPanel';
import MorePanel from './MorePanel';
import { MessageType } from './MessageList';

const emojiList = [
  "😀", "😏", "😊", "💔", "😭", "😒", "👍", "😳", "😅", "😎",
  "🥰", "😠", "😴", "😢", "😓", "😡", "😋", "😂", "😘",
  "🤔", "😮", "😑", "😞", "😆", "😯", "😐", "😃",
  "😅", "🤐", "😲", "👻", "🥵", "🥶", "🥳", "🤩",
  "😍", "🙏", "👋", "🎉", "🔥",
];

interface Props {
  onSend: (msg: MessageType) => void;
  scrollViewRef: React.RefObject<ScrollView | null>;
}

const audioRecorderPlayer = new AudioRecorderPlayer();

const InputPanel: React.FC<Props> = ({ onSend, scrollViewRef }) => {
  // 输入框内容
  const [input, setInput] = useState('');
  // 是否展示表情面板
  const [showEmoji, setShowEmoji] = useState(false);
  // 最近使用的表情
  const [recentEmojis, setRecentEmojis] = useState(emojiList.slice(0, 8));
  // 是否展示更多（加号）面板
  const [showMorePanel, setShowMorePanel] = useState(false);
  // 录音中标志
  const [recording, setRecording] = useState(false);
  // 录音开始时间戳
  const [recordStart, setRecordStart] = useState<number>(0);
  // 录音定时器，用于1分钟自动停止
  const recordTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  // 自动触发去重标志
  const sentByTimeoutRef = useRef(false);

  // 点击表情
  const handleEmojiPress = (emoji: string) => {
    setInput(input + emoji);
    setRecentEmojis((prev) => {
      const next = [emoji, ...prev.filter(e => e !== emoji)];
      return next.slice(0, 8);
    });
  };

  // 发送文本消息或展开更多面板
  const handlePlusOrSend = () => {
    if (input.trim()) {
      // 有内容时发送文本
      onSend({ type: 'text', text: input });
      setInput('');
      setShowEmoji(false);
      setShowMorePanel(false);
      setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100);
    } else {
      // 无内容时展开或收起加号功能面板
      setShowMorePanel(show => !show);
      setShowEmoji(false);
    }
  };

  // 开始录音
  const startRecording = async () => {
    try {
      setRecording(true);
      setRecordStart(Date.now());
      sentByTimeoutRef.current = false; // 每次录音前重置
      await audioRecorderPlayer.startRecorder();
      // 设置60秒自动发送
      recordTimeoutRef.current = setTimeout(() => {
        stopRecordingAndSend(true); // 自动超时
      }, 60 * 1000);
    } catch (err) {
      setRecording(false);
    }
  };

  // 结束录音并发送语音消息（isTimeout: true为自动，false为手动）
  const stopRecordingAndSend = async (isTimeout = false) => {
    if (!recording) return; // 防止多次触发
    if (isTimeout) {
      // 自动超时触发，正常发送并标记
      sentByTimeoutRef.current = true;
    } else {
      // 手动触发，如果刚自动发过就不再发
      if (sentByTimeoutRef.current) {
        sentByTimeoutRef.current = false; // 下次录音前自动重置
        return;
      }
    }
    // 清理定时器
    if (recordTimeoutRef.current) {
      clearTimeout(recordTimeoutRef.current);
      recordTimeoutRef.current = null;
    }
    setRecording(false);
    try {
      const result = await audioRecorderPlayer.stopRecorder();
      // 计算录音时长，最多60秒
      const duration = Math.max(1, Math.round((Date.now() - recordStart) / 1000));
      onSend({ type: 'voice', filePath: result, duration: Math.min(duration, 60) });
      setShowEmoji(false);
      setShowMorePanel(false);
      setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100);
    } catch (err) {
      setRecording(false);
    }
  };

  return (
    <View>
      {/* 输入区 */}
      <View style={styles.inputArea}>
        {/* 麦克风按钮：按下录音，松开发送 */}
        <TouchableOpacity
          onPressIn={startRecording}
          onPressOut={() => stopRecordingAndSend(false)}
        >
          <Text style={styles.icon}>{recording ? "录音中..." : "🎤"}</Text>
        </TouchableOpacity>
        {/* 文本输入框 */}
        <TextInput
          style={styles.input}
          placeholder="输入消息..."
          placeholderTextColor="#ccc"
          value={input}
          onChangeText={setInput}
          onSubmitEditing={handlePlusOrSend}
          returnKeyType="send"
          blurOnSubmit={false}
        />
        {/* 表情按钮 */}
        <TouchableOpacity
          onPress={() => {
            Keyboard.dismiss();
            setShowEmoji(show => !show);
            setShowMorePanel(false);
          }}
        >
          <Text style={styles.icon}>😊</Text>
        </TouchableOpacity>
        {/* 发送/加号按钮 */}
        <TouchableOpacity onPress={handlePlusOrSend}>
          <Text style={styles.icon}>{input.trim() ? '发送' : '➕'}</Text>
        </TouchableOpacity>
      </View>
      {/* 表情面板 */}
      {showEmoji && <EmojiPanel recentEmojis={recentEmojis} onEmojiPress={handleEmojiPress} onClose={() => setShowEmoji(false)} />}
      {/* 加号功能面板 */}
      {!showEmoji && showMorePanel && <MorePanel />}
    </View>
  );
};

const styles = StyleSheet.create({
  inputArea: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: adapt(8),
    borderTopWidth: 1,
    borderColor: '#333',
    backgroundColor: '#111',
  },
  input: {
    flex: 1,
    height: adapt(40),
    backgroundColor: '#222',
    marginHorizontal: adapt(8),
    borderRadius: adapt(20),
    paddingHorizontal: adapt(12),
    color: '#fff',
    fontSize: adaptFontSize(16),
  },
  icon: {
    fontSize: adaptFontSize(20),
    color: '#fff',
    paddingHorizontal: adapt(4),
  },
});

export default InputPanel;